package org.example.algorithm.sort;

import lombok.extern.slf4j.Slf4j;
import org.reflections.Configuration;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SortAlgorithmFactory {

    private final Map<SortType, ISortAlgorithm> algorithmMap = new ConcurrentHashMap<>();

    private SortAlgorithmFactory() {
        Configuration configuration = new ConfigurationBuilder()
                .forPackages(SortAlgorithmFactory.class.getPackage().getName())
                .filterInputsBy(new FilterBuilder().includePackage(SortAlgorithmFactory.class.getPackage().getName()))
                .addScanners(new SubTypesScanner())
                .addScanners(new FieldAnnotationsScanner());
        Reflections reflections = new Reflections(configuration);
        Set<Class<? extends ISortAlgorithm>> set = reflections.getSubTypesOf(ISortAlgorithm.class);
        for (Class<?> clazz : set) {
            if (!Modifier.isAbstract(clazz.getModifiers())) {
                try {
                    ISortAlgorithm sortAlgorithm = (ISortAlgorithm) clazz.getDeclaredConstructor().newInstance();
                    algorithmMap.put(sortAlgorithm.getSortType(), sortAlgorithm);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    private static class SortAlgorithmFactoryHolder {
        private static final SortAlgorithmFactory newInstance = new SortAlgorithmFactory();
    }

    public static SortAlgorithmFactory getInstance() {
        return SortAlgorithmFactoryHolder.newInstance;
    }

    public ISortAlgorithm getSortAlgorithmBySortType(SortType sortType) {
        return algorithmMap.getOrDefault(sortType, null);
    }
}
